<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :title="title"
    width="60%">
    <el-row :gutter="40">
      <el-col :span="10">
        <el-card shadow="never" style="padding: 5px">
          <el-input
            v-model="filterText"
            :placeholder="`${$t('searchKeyword')}`"
          />
          <!-- <el-tree
            ref="tree"
            :props="treeProps"
            :data="treeData"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            check-strictly
            node-key="id"
            show-checkbox
            check-on-click-node
            @current-change="checkChange"
          /> -->
          <el-tree
            ref="tree"
            :props="treeProps"
            :data="treeData"
            :filter-node-method="filterNode"
            check-strictly
            default-expand-all
            node-key="id"
          >
            <span slot-scope="{ node, data }">
              <span
                @click="checkChange(node, data)"
              > <el-checkbox :disabled="node.level !== 4 " :value="data.checked" style="paddingRight: 10px"/>{{ node.label }}</span>
          </span></el-tree>
        </el-card>
      </el-col>
      <el-col :span="14">
        <dynForm
          ref="dataForm"
          :info-form="searchForm"
          :rules="rules"
          :search-tags="searchTags"
          :is-inline="false"
          :select-list="selectList"/></el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button icon="el-icon-circle-close" @click="handleClose">{{
        $t("cancel")
      }}</el-button>
      <el-button v-btnThrottle="doSave" type="primary" icon="el-icon-receiving">{{
        $t("save")
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getInfo, doUpdate, doAdd } from '@/api/OEE/timeConfig'
// import { getEqpListTree } from '@/api/maintenance/planManage'
import { getTreeList } from '@/api/equipment/prodTreeNode'

export default {
  name: 'TimeConfigurationDialog',
  components: {},
  props: {},
  data() {
    return {
      title: '',
      dialogVisible: false,
      // startTime, endTime进行双绑重新触发render
      searchForm: {
        fixedTime: false,
        startTime: undefined,
        endTime: undefined
      },
      searchTags: [
        { label: this.$t('timeType'), prop: 'timeType', tag: 'DynInput' },
        { label: this.$t('fixedTime'), prop: 'fixedTime', tag: 'DynCheckbox', event: () => {
          this.searchForm.startTime = undefined
          this.searchForm.endTime = undefined
        } },
        { label: this.$t('startTime'), prop: 'startTime', tag: 'Dyntimerange', datatype: 'datetime', vif: () => {
          return this.searchForm.fixedTime
        } },
        { label: this.$t('endTime'), prop: 'endTime', tag: 'Dyntimerange', datatype: 'datetime', vif: () => {
          return this.searchForm.fixedTime
        } },
        { label: this.$t('startTime'), prop: 'startTime', tag: 'DynTimePicker', vif: () => {
          return !this.searchForm.fixedTime
        } },
        { label: this.$t('endTime'), prop: 'endTime', tag: 'DynTimePicker', vif: () => {
          return !this.searchForm.fixedTime
        } },
        { label: this.$t('remark'), prop: 'remark', tag: 'DynTextarea', row: 2 }
      ],
      rules: {
        timeType: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('timeType')}`, trigger: 'blur' }],
        startTime: [{ required: true, message: `${this.$t('pleaseSelect')}${this.$t('startTime')}`, trigger: 'blur' }],
        endTime: [{ required: true, message: `${this.$t('pleaseSelect')}${this.$t('endTime')}`, trigger: 'blur' }]
      },
      selectList: {},
      filterText: '',
      treeProps: { label: 'name', children: 'children' },
      treeData: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    doSave() {
      const flattenTree = (root) => {
        if (!root || !root.length) return
        const list = []
        root.forEach(node => {
          const { children, checked, id } = node
          if (checked) {
            list.push(id)
          }
          if (children && children.length) {
            const tempList = flattenTree(children)
            list.push(...tempList)
          }
        })
        return list
      }
      const valiForm = new Promise((resolve, reject) => {
        this.$refs['dataForm'].$refs['dynForm'].validate((valid) => {
          valid ? resolve(valid) : reject(valid)
        })
      })
      Promise.all([this.valiEqpList(flattenTree(this.treeData)), valiForm]).then(() => {
        if (this.searchForm.id) {
          // 根据后端接口需要需要进行转换
          doUpdate({ ...this.searchForm, eqpIdList: flattenTree(this.treeData), fixedTime: this.searchForm.fixedTime ? 1 : 0 }).then(res => {
            this.$betterTips(res, this.handleUpdate, this.handleClose)
          })
        } else {
          // 根据后端接口需要需要进行转换
          doAdd({ ...this.searchForm, eqpIdList: flattenTree(this.treeData), fixedTime: this.searchForm.fixedTime ? 1 : 0 }).then(res => {
            this.$betterTips(res, this.handleUpdate, this.handleClose)
          })
        }
      }).catch(() => {
        return false
      })
    },
    // 触发父组件更新
    handleUpdate() {
      this.$emit('initList')
    },
    async handleOpen(val) {
      this.dialogVisible = true
      if (val && val.id) {
        this.title = this.$t('modify')
        const res = await getInfo({ id: val.id })
        const list = await getTreeList()
        const { data } = res
        // 设置checked属性
        this.treeData = this.formatTreeChecked(list.data, data.eqpIdList)
        this.searchForm = {
          ...data,
          fixedTime: data.fixedTime === 1
        }
      } else {
        this.title = this.$t('add')
        await this.getEqpTypeListTree()
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].$refs['dynForm'].clearValidate()
      })
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    valiEqpList(list) {
      return new Promise((resolve, reject) => {
        if (!list.length) {
          this.$notify.error({
            message: '请选择机台设备',
            duration: 0
          })
          reject(false)
        }
        resolve(true)
      })
    },
    // checkChange(data, node) {
    //   if (node.level === 3) {
    //     this.$refs.tree.setCurrentKey(data.id)
    //   } else {
    //     this.$refs.tree.setCurrentKey(null)
    //   }
    // },
    checkChange(node, data) {
      if (node.level === 4) {
        data.checked = !data.checked
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 获取所有的设备类型
    async getEqpTypeListTree() {
      const res = await getTreeList()
      const formatTree = (root) => {
        return (root || []).map(node => {
          const { id, name, children } = node
          return {
            id,
            name,
            checked: false,
            children: formatTree(children)
          }
        })
      }
      this.treeData = formatTree(res.data)
    },
    formatTreeChecked(root, checkedList) {
      return (root || []).map(node => {
        const { id, name, children } = node
        return {
          id,
          name,
          checked: checkedList.includes(id),
          children: this.formatTreeChecked(children, checkedList)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
